﻿using ManaSky.Common.Models;
using ManaSky.Model;
using ManaSky.SSO.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;

namespace ManaSky.Core.Attributes
{
    /// <summary>
    /// 过滤器
    /// </summary>
    public class CustomAuthorizationFilterAttribute : Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            //如果方法上面标记了AllowAnonymous特性，则跳过登录校验-以及权限检查
            if (context.ActionDescriptor.EndpointMetadata.Any(item => item is AllowAnonymousAttribute))
                return;
            var authHeader = context.HttpContext.Request.Headers["Authorization"];
            if (string.IsNullOrWhiteSpace(authHeader))
            {
                //var json =  JsonConvert.SerializeObject(new OperationResult(OperationResultType.Error, "保存失败"));
                //此接口必须携带token访问！
                context.Result = new ContentResult()
                {

                    Content = JsonConvert.SerializeObject(ApiRequest.LoginExpired("此接口必须携带Token访问，请登录携带Token访问！")),
                    ContentType = "application/json;charset=utf-8",
                    StatusCode = StatusCodes.Status200OK
                };
            }
            else
            {
                authHeader = authHeader.ToString().Replace("Bearer", "").Trim();//去掉Bearer字串
                if (string.IsNullOrWhiteSpace(authHeader))
                {
                    context.Result = new ContentResult()
                    {
                        Content = JsonConvert.SerializeObject(ApiRequest.LoginExpired("Token验证失败：您没有权限调用此接口，请登录重新获取Token")),
                        ContentType = "application/json;charset=utf-8",
                        StatusCode = StatusCodes.Status200OK
                    };
                }
                else
                {
                    var payload = JwtHelper.Decode(authHeader);
                    if (payload.ValidTo < DateTime.UtcNow)
                    {
                        context.Result = new ContentResult()
                        {
                            Content = JsonConvert.SerializeObject(ApiRequest.LoginExpired("Token已过期，请登录重新获取Token")),
                            ContentType = "application/json;charset=utf-8",
                            StatusCode = StatusCodes.Status200OK
                        };
                    }
                }
            }
        }
    }
}
